(function ($) {
    function WrongData() {
        app.alert('AlertDlg', 'Ошибка', 'Данные введены неправильно !!!', 'ipdepo-icon-stop32');
    }
    //
    // Каталог автомобилей
    //
    function Catalogue(area_id) {
        var vdiv = area_id+'Tab';
		var area = $('#'+area_id);

		area.css({'overflow':'hidden'})
		area.html('<div id="'+vdiv+'Pager"></div><table id="'+vdiv+'"></table>');
        
		var pager = $('#' + vdiv + 'Pager');
        var el_vend_id;
        var el_vend_name;
        var auto_vend_name = '';
        var el_model_id;
        var el_model_name;
        var auto_model_name = '';
        var el_modif_id;
        var el_modif_name;
        var auto_modif_name = '';
        var el_engine;
        var gritab;
        var col_order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        var col_names = ['ID', 'Регион', 'Марка(ID)', 'Марка', 'Модель(ID)', 'Модель', 'Модификация(ID)', 'Модификация',
                        'Фото', 'Выпущен', 'Пробег', 'Цена', 'Комментарий'];
        var col_model = [
		    { name: 'id', index: 'car_id', hidden: true, width: 50, editable: false, fixed: true },
			{ name: 'city_id', index:'city_id', hidden: false, width:110, 
				editable: true, edittype:'select', editoptions:{value:""}
			},         
		    { name: 'vend_id', index: 'vend_id', hidden: true, width: 50, editable: true,
            	editoptions: { maxlength: "16", style: "width:95%;min-width:200px;", dataInit: function (el) { el_vend_id = el; } }
		    },
		    { name: 'vend_name', index: 'vend_name', hidden: true, width: 150, editable: true, editrules:{edithidden:true},
		        editoptions: { maxlength: "50", style: "width:95%;min-width:200px;", dataInit: SetVendorHack }
		    },
		    { name: 'model_id', index: 'model_id', hidden: true, width: 50, editable: true,
		        editoptions: { maxlength: "16", style: "width:95%;min-width:200px;", dataInit: function (el) { el_model_id = el; } }
		    },
		    { name: 'model_name', index: 'model_name', hidden: true, width: 200, editable: true, editrules:{edithidden:true},
		        editoptions: { maxlength: "50", style: "width:95%;min-width:200px;", dataInit: SetModelHack }
		    },
		    { name: 'modif_id', index: 'modif_id', hidden: true, width: 50, editable: true,
		        editoptions: { maxlength: "16", style: "width:95%;min-width:200px;", dataInit: function (el) { el_modif_id = el; } }
		    },
		    { name: 'modif_name', index: 'modif_name', hidden: false, width: 300, editable: true,  edittype:'select'
		    },
			{ name:'photo', index:'photo', hidden: false, width:50, editable: false,
				formatter: No_Yes 
			},
		    { name: 'p_date', index: 'p_date', hidden: false, width: 100, editable: true,
		        editoptions: { maxlength: "4", style: "width:95%;min-width:200px;"}
		    },
		    { name: 'km_count', index: 'km_count', hidden: false, width: 100, editable: true,
		        editoptions: { maxlength: "8", style: "width:95%;min-width:200px;"}
		    },
            { name: 'price', index: 'price', hidden: false, width: 100, editable: true,
			    editoptions: { maxlength: "8", style: "width:95%;min-width:200px;"}
            },
		    { name: 'comment', index: 'comment', hidden: false, width: 200, editable: true,
		        editoptions: { maxlength: "255",  style: "width:95%;min-width:200px;" }
		    }
        ];

        var jqgo = {
            url: 'callbacks.php',
            editurl: 'callbacks.php',
            datatype: 'json',
            postData: { source: 'CarCatalogue', oper: 'page' },
            emptyrecords: true,
            autowidth: false,
            //		    scrollOffset: 22,
            gridview: true,
            hidegrid: false,
            hoverrows: true,
            recordpos: 'right',
            scrollrows: true,
            multiselect: true,
            multiselectWidth: 40,
            multiboxonly: true,
            mtype: 'POST',
            colNames: col_names,
            colModel: col_model,
            page: 1,
            pager: pager,
            pagerpos: 'right',
            rowNum: 100,
            rowList: [100, 500, 2000],
            //		    viewrecords: true,
            loadui: 'disable',
            toolbar: [false, 'top'],
			toppager: false,
            filterbar: false,
            shrinkToFit: false,
			height: 'auto',
//            height: tabHeight,
            width: $('#'+area_id).innerWidth() - 2,
            sortname: 'modif_name',
            sortorder: 'asc',
            sortable: true,
            caption: '',
            loadError: function () {
                alert("Ошибка загрузки даных");
            },
            loadComplete: function (data) {
                switch( data.userdata.errcode ) {
                    case 0:
                        if ($.browser.msie || $.browser.webkit) {
                            $('#' + vdiv + ' tr.jqgrow td').height(21);
                        }
                        break;
                    case 999:    
                        alert(data.userdata.errmess);
						app.customer = { uname:'', cust_id:0 };
                        document.location = 'index.php';
                        break;
                    default:
                        alert( data.userdata.errmess );
                        break;
                }                

                var id_col = $('#' + vdiv + ' td[aria-describedby="' + vdiv + '_id"]');
                var photo_col = $('#' + vdiv + ' td[aria-describedby="' + vdiv + '_photo"]');
                if (photo_col) {
                    for (var i = 0; i < id_col.length; i++) {
						var ph_dom = $(photo_col[i]);
						var car_id = $(id_col[i]).text();
						if( ph_dom.html() ) {
							ph_dom.attr( 'rel', '#car_'+car_id+'_tbl' );
							
							ph_dom.cluetip({
								local: true,
								cluetipClass: 'imag',
								width: 82,
								height: 61,
								dropShadow: true,
								waitImage: false,
								positionBy: 'mouse',
								showTitle: false,
								escapeTitle: true,
							});
							ph_dom.click(car_id,function(ev){
								gritab.resetSelection().setSelection(ev.data); 
							});
						}
                    }
                }

            },
            ondblClickRow: function (id, iRow, iCol) {
				if( iCol == 9 ) {
					var row_data = gritab.getRowData(id);
					ImageUpload( id, id+' / '+row_data.modif_name ); 
					return;
				}
                $('#' + vdiv).jqGrid('editGridRow', id,
                {
                    modal: true,
                    jqModal: true,
                    zIndex: app.jqgrid_form_min_z_index,
                    closeOnEscape: true,
// Autocomplete Select
//                    savekey: [true, 13],
                    editData: { source: 'CarCatalogue' },
                    afterShowForm: onShowEditForm,
                    afterSubmit: responseOnSubmit,
                    viewPagerButtons: false,
                    closeAfterEdit: true
                }
                );
            }
        };

		$(window).resize( function() {
			gritab.setGridWidth( $('#'+area_id).innerWidth() - 2 );
			gritab.setGridHeight( $('#'+area_id).innerHeight() - 50 );
		} );
		
		function getInitData() {
            $.post('callbacks.php', { source: 'CarUtils', oper: 'cities' },
            function (rsp, textStatus) {
                if (rsp.errcode) {
                    if (rsp.errcode == '999') { 
						alert(rsp.errmess);
						app.customer = { uname:'', cust_id:0 };
						location.href = 'index.php'; 
					}
                    else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                    return;
                }
				var ct = rsp.data.cities;
				var i, ctl = '';
                for( i=0; i<ct.length; i++ ) {
					if( ctl ) ctl += ';';
					ctl += ct[i].value+':'+ct[i].label;
                }
				gritab.setColProp('city_id',{editoptions:{value:ctl}}); 
//				jqgo.colModel[1].editoptions.value = ctl;
            }, 
            'json');  			
		}

		function onShowAddForm() {
			el_modif_name = $('#tr_modif_name .FormElement');
			el_modif_name.find('*').remove();
			el_modif_name
				.css({'width':'95%', 'min-width':'200px'})
				.bind('change', function(e) { $(el_modif_id).val(this.value); } );
			$('#tr_city_id .FormElement').css({'width':'95%', 'min-width':'200px'});
			$('div#editmod' + vdiv).shadow();
		}
		
		function onShowEditForm() {
			el_modif_name = $('#tr_modif_name .FormElement');
			el_modif_name.css({'width':'95%', 'min-width':'200px'})
			.bind('change', function(e) { 
				$(el_modif_id).val(this.value);
			} );
			$('#tr_city_id .FormElement').css({'width':'95%', 'min-width':'200px'});
			FillModifSelect();
			$('div#editmod' + vdiv).shadow();
		}
		
// Заполнение селекта модификаций
		function FillModifSelect() {
			el_modif_name.find('*').remove();
			var reqData = { 
				node_id: $(el_vend_id).val()+'.'+$(el_model_id).val(), 
				source: "CarTree", oper: "tree" 
			};
            $.post('callbacks.php', reqData,
            function (data, textStatus) {
				var subkeys;
				for( var i=0; i<data.length; i++ ) {
					subkeys = data[i].key.split('.');
					if (subkeys.length == 3) {
						el_modif_name.append('<option value="'+subkeys[2]+'">'+data[i].title+'</option>');
					}
                }
				var m = $(el_modif_id).val();
				if( !m ) {
					m = el_modif_name.find('option:first').val();
					el_modif_name.val(m);
					$(el_modif_id).val(m);
				}
				else {
					el_modif_name.val( $(el_modif_id).val() );
				}
            },        
            'json');
		}
		
// Photo
		function No_Yes( cellval, opt, rowObj ) {
			if( cellval != "" ) {
				newval = '<div class="ui-icon ui-icon-image"> \
					<img id="car_'+opt.rowId+'_tbl" style="display:none;position:absolute;" \
					src="getimg.php?source=CarImages&oper=get&im=tbl&car_id='+opt.rowId+'&rand='+Math.random()+'"></div>';
//						<img id="car_'+opt.rowId+'_tbl" style="display:none;position:absolute;" src="'+cellval+'"></div>';
			}
			else newval = '';
			return newval;
		}
        
// Создадим jqGrid
        gritab = $('#' + vdiv).jqGrid(jqgo);

		getInitData();
		
// Индикация ошибок при вводе, ред., удал.
        function testNewData(pd, formid) {
            var result = true, mess = '';
            if( pd.vend_id == '' || pd.model_id == '' || pd.modif_id == '' || pd.p_date == '') {
                result = false;
                mess = 'Данные введены с ошибками !!!';
            }
            return[result,mess];
        }
        
// Индикация серверных ошибок добавления, ред., удал.
        function responseOnSubmit(response, postdata) {
            var rsp = $.parseJSON(response.responseText);
            var success = true;
            var msg = '';

            if (rsp.errcode) {
                success = false;
                msg = rsp.errmess;
                if (rsp.errcode == '999') { 
					alert(rsp.errmess);
					app.customer = { uname:'', cust_id:0 };
					location.href = 'index.php'; 
				}
            }
			if( success && postdata.oper == 'add' )
				el_modif_name.find('*').remove();
				
            return [success, msg];
        }

        // Навигатор - обновить
        gritab.jqGrid('navGrid', '#' + vdiv + 'Pager',
// Параметры инструментов
        {
            add: true, addtext: 'Создать', 
			del: true, deltext: 'Удалить', 
			edit: true, edittext: 'Изменить', 
			search: false,
            refresh: true, refreshtext: 'Обновить', afterRefresh: function () { gritab.resetSelection(); }
        },
// Параметры редактирования
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
//            savekey: [true, 13],
            closeOnEscape: true,
            editData: { source: 'CarCatalogue' },
            afterShowForm: onShowEditForm,
            beforeSubmit: testNewData, 
            afterSubmit: responseOnSubmit,
            viewPagerButtons: false,
            closeAfterEdit: true
        },
// Параметры добавления
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
//            savekey: [true, 13],
            closeOnEscape: true,
            editData: { source: 'CarCatalogue' },
            afterShowForm: onShowAddForm,
            beforeSubmit: testNewData, 
            afterSubmit: responseOnSubmit
        },
// Параметры удаления
        {
            modal: true,
            jqModal: true,
            width: 'auto',
            zIndex: app.jqgrid_form_min_z_index,
            closeOnEscape: true,
            delData: { source: 'CarCatalogue' },
            afterShowForm: function () {
                $('div#delmod' + vdiv).shadow();
/*
                $('#DelTbl_' + vdiv + ' tr:eq(2) td').html(
                    '<p style="font-weight:700; text-align:center;">ВНИМАНИЕ !!!</p>' +
                    'Удаление записи(сей)  в этой таблице повлечет за собой<br>' +
                    'удаление соответствующих записей в таблице "Архив цен"' +
                    '<p style="text-align:center;">Выполнить удаление ?</p>'
                );
*/
				},
            afterSubmit: responseOnSubmit
        }
        );
        

// Пользовательский навигатор
        gritab.jqGrid('navButtonAdd', '#' + vdiv + 'Pager', {
            caption: 'Фото',
            title: 'Загрузить фотоснимок',
            buttonicon: 'ui-icon-image',
            onClickButton: function() { 
				var curr_id = gritab.getGridParam('selrow');
				if( !curr_id ) return;
				var row_data = gritab.getRowData(curr_id);
				ImageUpload( curr_id, curr_id+' / '+row_data.modif_name ); 
			}
        });

		$('td#' + vdiv + 'Pager_left').css({'width':'383px'});
		
//        gritab.filterToolbar({ searchOnEnter: false, afterSearch: function () { } });

        function SetVendorHack(el) {
            el_vend_name = el;
            $(el).autocomplete({
                source: function (request, responce) {
                    $.post('callbacks.php', { source: 'VendorDictionary', oper: 'find', term: request.term },
                    function (rsp, textStatus) {
                        if (rsp.errcode) {
                            if (rsp.errcode == '999') { 
								alert(rsp.errmess);
								app.customer = { uname:'', cust_id:0 };
								location.href = 'index.php'; 
							}
                            else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                            responce();
                            return;
                        }
                        if (rsp.data) {
                            responce($.map(rsp.data, function (item) {
                                return { label: item.name, value: item.value }
                            }));
                            return;
                        }
                        responce();
                    }, 
                    'json');
                },
                minLength: 2, autoFocus: true,
                focus: function (event, ui) { return false; },
                select: function (event, ui) {
                    $(el_vend_id).val(ui.item.value);
                    auto_vend_name = ui.item.label;
                    $(el_vend_name).val(auto_vend_name);
                    
                    $(el_model_id).val("");
                    auto_model_name = "";
                    $(el_model_name).val("");

                    $(el_modif_id).val("");
                    auto_modif_name = "";
                    $(el_modif_name).find('*').remove();
                    return false;
                }
            });
            $(el_vend_name).bind( 'change', function () {
// Проверка, что данные получены автозаполнением. 
                if( $(el_vend_id).val() == "" || $(el_vend_name).val() != auto_vend_name ) {
                    $(el_vend_id).val('')
                    auto_vend_name = '';
                }
                $(el_model_id).val("");
                auto_model_name = "";
                $(el_model_name).val("");

                $(el_modif_id).val("");
                auto_modif_name = "";
                $(el_modif_name).find('*').remove();
			});
        }

        function SetModelHack(el) {
            el_model_name = el;
            $(el).autocomplete({
                source: function (request, responce) {
                    $.post('callbacks.php', { source: 'ModelDictionary', oper: 'find', term: request.term, vend_id: $(el_vend_id).val() },
                    function (rsp, textStatus) {
                        if (rsp.errcode) {
                            if (rsp.errcode == '999') { 
								alert(rsp.errmess);
								app.customer = { uname:'', cust_id:0 };
								location.href = 'index.php'; 
							}
                            else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                            responce();
                            return;
                        }
                        if (rsp.data) {
                            responce($.map(rsp.data, function (item) {
                                return { label: item.name, value: item.value }
                            }));
                            return;
                        }
                        responce();
                    }, 
                    'json');
                },
                minLength: 2, autoFocus: true,
                focus: function (event, ui) { return false; },
                select: function (event, ui) {
                    $(el_model_id).val(ui.item.value);
                    auto_model_name = ui.item.label;
                    $(el_model_name).val(auto_model_name);
					
					FillModifSelect();
                    return false;
                }
            });
            $(el_model_name).bind( 'change', function () { 
                if( $(el_model_id).val() == "" || $(el_model_name).val() != auto_model_name ) { 
                    auto_model_name = '';
                    $(el_model_id).val("");
					
					$(el_modif_id).val("");
					auto_modif_name = "";
					$(el_modif_name).find('*').remove();
                }
            });            
        }

// Просмотр/Загрузка изображения
function ImageUpload(car_id, title) {
    if( car_id == '' ) return; 
    
    var wimg = 'photo_'+car_id;

    if($('#'+wimg).html()) { $('#'+wimg).dialog('moveToTop'); return; }
    
    $('body').append('<div id="'+wimg+'"></div>');
// getimg.php?source=CarImages&oper=get&im=img&index=1&car_id='+car_id
    $('#'+wimg).html(
		'<div id="upload-mess" class="upload-mess ui-widget ui-corner-all ui-widget-content ui-state-error"></div> \
		<div style="height:480px;width:640px"><img id="car-img" style="height:100%;width:100%" \
		src="getimg.php?source=CarImages&oper=get&im=img&car_id='+car_id+'&rand='+Math.random()+'"></div> \
		<table style="table-layout:fixed;width:100%;margin-top:4px;"><col><col style="width:300px"> \
		<tr><td ><div id="progressbar"></div></td><td> \
		<button id="end-upload-bt" style="float:right;margin-left:8px;">Закрыть</button> \
		<button id="del-upload-bt" style="float:right;margin-left:8px;">Удалить</button> \
		<div  style="float:right;" class="input-file-emu"> \
			<span id="sel-upload-bt" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icons"> \
			<span class="ui-button-icon-primary ui-icon ui-icon-folder-open"></span> \
			<span class="ui-button-text">Изменить</span></span> \
			<input id="fileupload" class="fileupload-button" type="file" name="files[]"> \
		</div></td></tr></table> \
		<div class="ui-widget-content ui-state-disabled ui-corner-all" \
			style="width:100%; height:52px; margin-top:4px; overflow-y:auto;"> \
			<div style="margin:8px 16px;font-size:smaller;">\
			Требования к загружаемым файлам. Тип файла: .jpg, .png, .gif. Размер файла: до 2Мб. \
			Формат изображения: 3х4. Размер изображения: от 320х240 до 1280х960.</div> \
		<div>'
	);
//			<div style="margin:8px 16px;font-size:smaller;">\

	$('#fileupload').hover(
		function() { $('#sel-upload-bt').addClass('ui-state-hover'); },
		function() { $('#sel-upload-bt').removeClass('ui-state-hover'); }
	);
	$('#fileupload').mousedown(function() { $('#sel-upload-bt').addClass('ui-state-active'); } );
	$('#fileupload').mouseup(function() { $('#sel-upload-bt').removeClass('ui-state-active'); } );
	
	$( "#progressbar" ).progressbar({ value: 100 }).progressbar('disable');
	
    $('#fileupload').fileupload({
        dataType: 'json',
		url: 'callbacks.php',
		formData: [
			{name:'source',value:'CarImages'},
			{name:'oper',value:'edit'},
			{name:'im', value:'img'},
			{name:'car_id', value: car_id }
		],
		singleFileUploads: true,
		progressInterval: 50,
		bitrateInterval: 100,
		start: function() { $( "#progressbar" ).progressbar('enable').progressbar({ value: 0 }); },
		add: function(e, data ) {
			data.submit();
		},
		progress: function (e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$( "#progressbar" ).progressbar( 'value', progress );
		},
        done: function (e, data) {
			var rsp = data.result[0];
			$( "#progressbar" ).progressbar( 'value', 100 ).progressbar('disable');
			if( typeof rsp.error != 'undefined' ) {
                if (rsp.error.errcode == '999') { 
						alert(rsp.error.errmess);
						app.customer = { uname:'', cust_id:0 };
						location.href = 'index.php'; 
				}
				$('#upload-mess').html(rsp.error.errmess)
                    .fadeIn('slow', function() {
                        setTimeout( function() { $('#upload-mess').fadeOut('normal')}, 5000 );
                    });
				return;
			}
//			$('#car-img').attr('src',rsp.img_url);
			$('#car-img').attr('src','getimg.php?source=CarImages&oper=get&im=img&car_id='+car_id+'&rand='+Math.random());
			gritab.trigger("reloadGrid");
        }
    });
	$('#end-upload-bt').button();
	$('#end-upload-bt').click(function() { $('#'+wimg).dialog('close');	});
	$('#del-upload-bt').button({icons:{primary: "ui-icon-trash"}});
	$('#del-upload-bt').click(function() {
		data = { source:'CarImages', oper:'del', car_id: car_id, index: 0 };
		$.post('callbacks.php', data, function( rsp, textStatus) {
            if( rsp.errcode ) {
                if (rsp.errcode == '999') { 
					alert(rsp.errmess);
					app.customer = { uname:'', cust_id:0 };
					location.href = 'index.php'; 
				}
				$('#upload-mess').html(rsp.errmess).fadeIn('slow', function() {
                        setTimeout( function() { $('#upload-mess').fadeOut('normal')}, 5000 );
                });
				return;
            }
			$('#car-img').attr('src','getimg.php?source=CarImages&oper=get&im=img&car_id='+car_id+'&rand='+Math.random());			
			gritab.trigger("reloadGrid");
		}, 'json');		
	});
	
    var im = $('#'+wimg+' #car-img');

    $('#'+wimg).dialog({
        title: title,
        modal: false,
		autoOpen: false,
        resizable: false,
        height: 'auto',
        width: 662,
        stack: true,
		open: function () { $('div[aria-labelledby="ui-dialog-title-' + wimg + '"]').shadow() },
        close: function() {
                $('#'+wimg).dialog("destroy");
                $('#'+wimg).remove();
             }
    });
    
	im.load( function() { 
		$('#'+wimg).dialog('open');
		$('#'+wimg).parent().resizable( {'aspectRatio':true, 'alsoResize':im.parent(), 'minHeight':350 } );			
	} );
}

		this.Destroy = function() {
			gritab.GridDestroy(vdiv);
			area.find('*').remove();
		};
		this.Resize = function() {
			gritab.setGridWidth( area.innerWidth() - 2 );
			gritab.setGridHeight( area.innerHeight() - 50 );
		}
		
	};  // End of create function definition


	function CatalogueProxy() {
		var TabsOb;
		this.Open = function( area_id ) {	TabsOb = new Catalogue( area_id ); };
		this.Close = function() { TabsOb.Destroy(); };
		this.Resize = function() { TabsOb.Resize(); };
	}
	
	app.CarsCatalogue = new CatalogueProxy();



/*	
    app.CarsCatalogue = {
		AreaID: '',
		TabObj: '',
		Open: function( area_id ) {
			this.AreaID = area_id;
			this.TabObj = ShowCarsCatalogue( area_id );
		},
        Close: function () {
            this.TabObj.GridDestroy(this.AreaID+'Tab');
			$('#'+this.AreaID+' *').remove();
        },
		Resize: function() {
			this.TabObj.setGridWidth( $('#'+this.AreaID).innerWidth() - 2 );
			this.TabObj.setGridHeight( $('#'+this.AreaID).innerHeight() - 50 );
		}
	};
*/

//
// Цены
//
    function GetPriceHistory(vdiv, vcar_id) {
        var el_vend_id;
        var pager = $('#' + vdiv + 'Pager');
        var gritab;
        var col_order = [0, 1, 2, 3, 4];
        var col_names = ['ID', 'Авто(ID)', 'Дата', 'Цена', 'Активна'];
        var col_model = [
		    { name: 'id', index: 'price_id', hidden: true, width: 50, editable: false, fixed: true },
		    { name: 'car_id', index: 'car_id', hidden: true, width: 50, editable: false, fixed: true },
		    { name: 'setdate', index: 'setdate', hidden: false, width: 150, editable: true },
//		            editoptions: { maxlength: "50",  style: "width:90%;min-width:200px;" } },
		    { name: 'price', index: 'price', hidden: false, width: 150, editable: true }, 
//                  editoptions: { maxlength: "50",  style: "width:90%;min-width:200px;" } },
		    { name: 'active', index: 'active', hidden: false, width: 100,
		        editable: true, edittype: 'checkbox', editoptions: { value: "1:0", defaultValue: "1" },
		        formatter: function (cellvalue, options, rowObject) {
		            return (cellvalue == '1') ? '<span cellval="1" class="ui-icon ui-icon-pin-s"></span>' : '<span cellval="0"></span>'
		        },
		        unformat: function (cellvalue, options, cell) { return $('span', cell).attr('cellval'); }
		    }
        ];
        var jqgo = {
            url: 'callbacks.php',
            editurl: 'callbacks.php',
            datatype: 'json',
            postData: { source: 'CarPrice', oper: 'page', fcar_id: vcar_id },
            emptyrecords: true,
            autowidth: false,
            //		    scrollOffset: 22,
            gridview: true,
            hidegrid: false,
            hoverrows: true,
            recordpos: 'right',
            scrollrows: true,
            multiselect: true,
            multiselectWidth: 40,
            multiboxonly: true,
            mtype: 'POST',
            shrinkToFit: true,
            colNames: col_names,
            colModel: col_model,
            page: 1,
            pager: pager,
            pagerpos: 'right',
            rowNum: 5,
            rowList: [5, 10, 20],
            //		    viewrecords: true,
            loadui: 'disable',
            toolbar: [false, 'top'],
            filterbar: false,
            height: 110,
            //		    width: 350,
            sortname: 'setdate',
            sortorder: 'desc',
            sortable: true,
            caption: '',
            loadError: function () {
                alert("Ошибка загрузки даных");
            },
            loadComplete: function (data) {
                switch( data.userdata.errcode ) {
                    case 0:
                        if ($.browser.msie || $.browser.webkit) {
                            $('#' + vdiv + ' tr.jqgrow td').height(21);
                        }
                        break;
                    case 999:    
                        alert(data.userdata.errmess);
						app.customer = { uname:'', cust_id:0 };
                        document.location = 'index.php';
                        break;
                    default:
                        alert( data.userdata.errmess );
                        break;
                }                
            },
            ondblClickRow: function (id) {
                $('#' + vdiv).jqGrid('editGridRow', id,
                {
                    modal: true,
                    jqModal: true,
                    zIndex: app.jqgrid_form_min_z_index,
                    closeOnEscape: true,
                    editData: { source: 'CarPrice', fcar_id: vcar_id },
                    afterShowForm: function (fm) {
                        var el = fm.find('#setdate');
                        BindCalendar(fm, el);
                        $('div#editmod' + vdiv).shadow();
                    },
                    afterSubmit: responseOnSubmit,
                    viewPagerButtons: false,
                    closeAfterEdit: true
                }
                );
            }
        };

// Создадим jqGrid
        gritab = $('#' + vdiv).jqGrid(jqgo);

// Индикация ошибок добавления, ред., удал.
        function responseOnSubmit(response, postdata) {
            var rsp = $.parseJSON(response.responseText);
            var success = true;
            var msg = '';

            if (rsp.errcode) {
                success = false;
                msg = rsp.errmess;
                if (rsp.errcode == '999') { 
					alert(rsp.errmess);
					app.customer = { uname:'', cust_id:0 };
					location.href = 'index.php'; 
				}
            }
            return [success, msg];
        }

        // Навигатор - обновить
        gritab.jqGrid('navGrid', '#' + vdiv + 'Pager',
        // Параметры инструментов
        {
            add: true, del: true, edit: true, search: false, refresh: true,
            afterRefresh: function () { gritab.resetSelection(); }
        },
// Параметры редактирования
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
            savekey: [true, 13],
            resize: false,
            closeOnEscape: true,
            editData: { source: 'CarPrice', fcar_id: vcar_id },
            afterShowForm: function (fm) {
                var el = fm.find('#setdate');
                BindCalendar(fm, el);
                $('div#editmod' + vdiv).shadow();
            },
            afterSubmit: responseOnSubmit,
            viewPagerButtons: false,
            closeAfterEdit: true
        },
// Параметры добавления
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
            savekey: [true, 13],
            resize: false,
            closeOnEscape: true,
            editData: { source: 'CarPrice', fcar_id: vcar_id },
            afterShowForm: function (fm) {
                var el = fm.find('#setdate');
                el.val($.datepicker.formatDate('dd.mm.yy', new Date()));
                BindCalendar(fm, el);
                $('div#editmod' + vdiv).shadow();
            },
            afterSubmit: responseOnSubmit
        },
// Параметры удаления
        {
            modal: true,
            jqModal: true,
            zIndex: app.jqgrid_form_min_z_index,
            resize: false,
            closeOnEscape: true,
            delData: { source: 'CarPrice', fcar_id: vcar_id },
            afterShowForm: function () { $('div#delmod' + vdiv).shadow() },
            afterSubmit: responseOnSubmit
        }
        );
        
/*
        // Пользовательский навигатор - вкл/выкл. тулбар фильтра
        gritab.jqGrid('navButtonAdd', '#' + vdiv + 'Pager', {
            caption: '',
            title: 'Включить тулбар фильтра',
            buttonicon: 'ui-icon-search',
            onClickButton: function () {
                gritab.setGridParam({ filterbar: !gritab.getGridParam('filterbar') });
                gritab[0].toggleToolbar();
            }
        });
*/
        gritab.filterToolbar({ searchOnEnter: false, afterSearch: function () { } });

        $("#gview_" + vdiv + " #gs_setdate").datepicker({
            dateFormat: "yy-mm-dd",
            showOn: "button",
            buttonImage: "img/calendar2.png",
            buttonImageOnly: true,
            buttonText: "Календарь",
            changeMonth: true,
            changeYear: true,
            onSelect: function (dateText) {
                $(this).focus();
                $(this).keydown();
            }
        });

        $("#gview_" + vdiv + " .ui-datepicker-trigger")
            .css({ 'cursor': 'pointer', 'position': 'relative', 'left': '-18px', 'top': '3px' });

        $("#gview_" + vdiv + " #gs_setdate").attr("title", "Формат ввода: 'ГГГГ-ММ-ДД'");
        $("#gview_" + vdiv + " #gs_active").attr("title", "1-активная цена, 0-все кроме ативной");

        function BindCalendar(fm, el) {
            el.datepicker({
                dateFormat: "dd.mm.yy",
                showOn: "button",
                buttonImage: "img/calendar2.png",
                buttonImageOnly: true,
                buttonText: "Календарь",
                changeMonth: true,
                changeYear: true
                //                onSelect: function (dateText) {
                //                    $(this).focus();
                //                    $(this).keydown();
                //                }
            });

            fm.find(".ui-datepicker-trigger")
                .css({ 'cursor': 'pointer', 'position': 'relative', 'left': '-18px', 'top': '3px' });
            el.attr("title", "Формат ввода: 'дд.мм.гггг'");
                
        }

        return gritab;
    };  // End of create function definition


    app.ShowPriceHistory = function (dlgID, car_id, prnt ) {
        var TabObj;
        var aldlg = $('#' + dlgID);
        var TabID = dlgID + 'Tab';
        var newdlg = $('#' + TabID).length ? false : true;

        if ($('#' + TabID).length) return;

        aldlg.html('<table id="' + TabID + '"></table><div id="' + TabID + 'Pager"></div>');

        TabObj = GetPriceHistory(TabID, car_id);

        aldlg.dialog(
        {
            modal: false, title: 'Архив цен',
            height: 'auto',
            width: 'auto',
            autoOpen: false,
            resizable: false,
            zIndex: app.ui_dialog_min_z_index,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                aldlg.dialog("destroy");
                if (TabObj) TabObj.GridDestroy(TabID);
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
                if( typeof prnt != 'undefined')
                    prnt.trigger("reloadGrid");
            }
        }
        );

        aldlg.dialog('open');
    }

    // ---------------------------------------------------------------------------
})(jQuery);
